#include "FileLoader.h"

#define FORMAT_VERIFICATION1		0x12ab65bf
#define FORMAT_VERIFICATION2		0x62a8b09e
#define FORMAT_VERIFICATION3		0x9127dc67
#define FORMAT_VERIFICATION4		0xaa443b10

#include "include/PowerLibraryEngine.h"
#include "include/ILog.h"

CFileLoader::CFileLoader()
{
}

CFileLoader::~CFileLoader()
{
}

CLoadedImage *CFileLoader::ImageLoad(u32 *Buffer,u32 Size)
{
	if (Buffer)
	{
		u32 Pointer = 0;
		u32 SizeHeader;
		ImageHeader ih;
		InternalReadGeneral(&SizeHeader,Buffer,4,&Pointer);
		InternalReadGeneral(&ih,Buffer,SizeHeader,&Pointer);

		// Internal verifications.
		if (ih.FormatVerification1 != FORMAT_VERIFICATION1)
		{
            pLogErrorRelease << "Format verification1 does not math. Is:" << ih.FormatVerification1 << ". Should be: " << FORMAT_VERIFICATION1 << endl;
		}

		if (ih.FormatVerification2 != FORMAT_VERIFICATION2)
		{
            pLogErrorRelease << "Format verification2 does not math. Is:" << ih.FormatVerification2 << ". Should be: " << FORMAT_VERIFICATION2 << endl;
		}

		if (ih.FormatVerification3 != FORMAT_VERIFICATION3)
		{
            pLogErrorRelease << "Format verification3 does not math. Is:" << ih.FormatVerification3 << ". Should be: " << FORMAT_VERIFICATION3 << endl;
		}

		if (ih.FormatVerification4 != FORMAT_VERIFICATION4)
		{
            pLogErrorRelease << "Format verification4 does not math. Is:" << ih.FormatVerification4 << ". Should be: " << FORMAT_VERIFICATION4 << endl;
		}

		CLoadedImage *Image = new CLoadedImage();
		Image->SetW(ih.Width);
		Image->SetH(ih.Height);
		Pointer >>=2;
		Image->CopyPixelsFrom(&(Buffer[Pointer]));
		pLogDebug << "Image loaded correctly" << endl;
		return Image;
	}
	else
	{
		pLogDebug << "Trying to load an image with pointer NULL" << endl;
	}

	return NULL;
}

void CFileLoader::InternalReadGeneral(void *Dest,void *Source,u32 Size,u32 *Position)
{
	u8 *SourceConv = (u8*)Source;
	u8 *Pointer = &(SourceConv[*Position]);
	memcpy(Dest,Pointer,Size);
	*Position += Size;
}

void CFileLoader::InternalReadu8(u8 *Dest,u8 *Source,u32 Size,u32 *Position)
{
	u32 PosOld = *Position;
	u32 PosChange = *Position * sizeof(u8);
	InternalReadGeneral(Dest,Source,Size*sizeof(u8),&PosChange);
	*Position = PosOld + Size;
}

void CFileLoader::InternalReadu32(u32 *Dest,u32 *Source,u32 Size,u32 *Position)
{
	u32 PosOld = *Position;
	u32 PosChange = *Position * sizeof(u32);
	InternalReadGeneral(Dest,Source,Size*sizeof(u32),&PosChange);
	*Position = PosOld + Size;
}
